// EG4ROOT.h -- an interface to ROOT for filling the generate
// sim data in a tree, and storing it in a root file
// Created: Sept. 24, 2024 by Asia SUN
// Last modified: Sept. 24, 2024 by Asia SUN

#include <ctime>
#include <iostream>
#include <TFile.h>
#include <TTree.h>
#include "EG4ROOT.h"
#include "EG4Data.h"
#include "EG4ParaManager.h"

using std::cout;
using std::endl;

EG4ROOT::EG4ROOT(){
  Initialize();
} // end ctor

EG4ROOT::~EG4ROOT(){}

void EG4ROOT::Initialize(){
  const Node &c = EG4ParaManager::Instance()->CtrlPara();
  char name[128] = "etf.root";
  if(c["rootfile"]) strcpy(name, c["rootfile"].as<string>().data());
  // sprintf(name, "etf%ld.root", time(0));
  fFile = new TFile(name, "RECREATE");
  fROOTFileName = name;
  fTree = new TTree("eg4", "G4 sim data tree for ETF");
  fData = new EG4Data();
  fTree->Branch("data", fData);
} // end of member function Initialize

// fill the tree
void EG4ROOT::Fill(){
  fTree->Fill();
} // end member function Fill

// write the tree and close the rootfile
void EG4ROOT::Finish(){
  cout << "fTree->GetEntries(): " << fTree->GetEntries() << endl;
  cout << "Data will be written into \033[1m" << fROOTFileName << "\033[0m" << endl;
  fFile->cd();
  fTree->Write("", TObject::kOverwrite);
  fFile->Close();
  // delete fData;
  cout << "Data has been written into \033[1m" << fROOTFileName << "\033[0m" << endl;
} // end member function Finish
